// pages/mall/proDetail/proDetail.js
import * as Api_Mall_product from '../../../api/mall/product'
import * as Api_Mall_product_Comment from '../../../api/mall/productComment'
import * as Api_Mall_Address from '../../../api/mall/address'
import * as Api_Mall_Cart from '../../../api/mall/shopCart'
import * as API_Collect from '../../../api/collect'

const config = require('../../../utils/config.js')
const QQMapWX = require('../../../utils/qqmap-wx-jssdk.min')
var qqMapSdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    animationData:{},
    //地址信息
    cityList:['北京市','上海市','天津市','重庆市'],
    cityName:'',
    districtName:'',
    addr:{},
    addrStr:'',
    addrId:'',
    // 商品信息
    productId:0,
    salesNum:0,
    currentPrice:0.00,
    oldPrice:0.00,
    productName:'',
    headshow:1,
    commentList:[],
    videoSrc:'',
    mainImg:[],
    secondaryImg:[],//副图
    richText:'',

    // 规格信息
    specs:[],
    specsNum:0,
    specsIndex:0,

    //评论
    params:{
      productId:0,
      pageNum:1,
      pageSize:1
    },
    lastPage:true,
    starList:[,,,,,],
    commontTotal:0,
    //收藏相关
    collect:false,
    collectModel:{}


  },
  autoplayVideo:function(e){
    let indexAll = e.currentTarget.dataset.indexAll;
    let commentList=this.data.commentList;
    commentList[indexAll].autoplay=true;
    this.setData({commentList:commentList});
    // debugger
  },
  swiperChange:function(e){
    let index=e.detail.current;
    console.info('当前轮播'+index);
    let mainVideo=this.data.mainVideo;

    if(!mainVideo){
      // 不要多次创建对象
      mainVideo= wx.createVideoContext('mainVideo');
      this.setData({mainVideo:mainVideo})
    }
    // debugger
    if(mainVideo){
      if(index==0){
        mainVideo.play();
      }else{
        mainVideo.pause();
      }
    
    }
   
   
  },
  collect(e){
    let that = this
    let params = {
      collectType:'mall_product',
      busId:that.data.productId,
      classifyId:that.data.classifyId
    }
    API_Collect.add(params).then(res=>{
      if(res.code == 200){
        let flag = this.data.collect
        this.setData({
          collect:!flag,
          collectModel:res.data
        })
        wx.showToast({
          title: '收藏成功',
        })
      }
    })
  },
  disCollect(){
    API_Collect.delCollect(this.data.collectModel.id).then(res=>{
      if(res.code == 200){
        let flag = this.data.collect
        this.setData({
          collect:!flag,
          collectModel:{}
        })
        wx.showToast({
          title: '取消收藏成功',
        })
      }
    })
  },
  goAddrList(e){
    wx.navigateTo({
      url: '../../mall/receAddressList/receAddressList',
    })
  },
  toBack:function(){
    wx.navigateBack({
      delta: 0,
    })
  },
  onPageScroll: function (e) {
    let opacity = 0
    opacity = (100- (e.scrollTop/2))/100
    this.setData({
      headshow: opacity
    })
  },
  videoloadedmetadata(e){
    let height=e.detail.height;
    let width=e.detail.width;
    this.setData({
      videoheight:height/width*100+'vw'
    })
  },
  loadAddr(){
    Api_Mall_Address.getDefault().then(res=>{
      if(res){
        this.setData({
          addrStr:res.provinceName+" "+res.cityName +" " +res.areaName +" "+res.streetName+" "+res.addressName,
          addrId:res.id
        })
      }else{
        this.initLocation()
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
// debugger
   this.redanimation = wx.createAnimation({
      duration: 600,
      timingFunction: 'ease',
    })
    // this.setData({redanimation:redanimation});
    API_Collect.query(options.id,'mall_product').then(res=>{
      if(res.data){
        this.setData({
          collect:true,
          collectModel:res.data,
        })
      }
    })

    this.loadAddr()
    let globalData=getApp().globalData;
     let statusBarHeightpx=globalData.statusBarHeightpx;
     this.setData({statusBarHeightpx:statusBarHeightpx});
     this.loadDetail(options.id)
     this.setData({
       'params.productId':options.id,
       productId:options.id
     })
     this.loadCoupons()
     this.loadComment()

  },
  loadCoupons(){
    let productId = this.data.productId
    this.chioceGuide = this.selectComponent("#coupons")
    this.chioceGuide.getList(productId)

  },
  loadComment(){
    Api_Mall_product_Comment.getList(this.data.params).then(res=>{
      let arr = this.data.commentList
      for(let item of res.rows){
        if(item.commentImages &&item.commentImages.length > 0){
          item.commentImages = item.commentImages.split(",")
        }
      }
      arr.push(...res.rows)
      this.setData({
        lastPage:res.lastPage,
        commontTotal:res.total,
        commentList:arr
      })
    })
  },
  toCommentList(e){
    wx.navigateTo({
      url: '../../mall/proCommonList/proCommonList?productId='+e.currentTarget.dataset.id
    })
  },
  loadDetail(e){
    Api_Mall_product.getDetail(e).then(res=>{
      const data = res.data
      let secondaryImg=data.secondaryImg;
      let secondaryImgArr=[];
      if(secondaryImg){
        secondaryImgArr=secondaryImg.split(",");
      }
   
      this.setData({
        videoSrc:data.video,
        mainImg:data.mainImg.split(","),
        secondaryImg:secondaryImgArr,
        productName:data.productName,
        currentPrice:data.specs[0].currentPrice,
        oldPrice:data.oldPrice,
        salesNum:data.salesNum,
        specsNum:data.specsNum,
        specs:data.specs,
        classifyId:data.classifyId,
        richText:data.richText
      })
    })
    this.addFoot()
  },
  preview(e){
    let arr = []
    for (let item of e.currentTarget.dataset.srcs){
      arr.push(item)
    }
    wx.previewImage({
      urls: arr,
      current:e.currentTarget.dataset.src
    })
  },
  toConfirm(){
    let that = this
    let specs = that.data.specs[that.data.specsIndex]
    let params = {
      'productId':that.data.productId+'',
      'specsId':specs.id+'',
      'countNum':1+''
    }
    let arr = [params]
    wx.navigateTo({
      url: '../../mall/orderConfirm/orderConfirm?params='+JSON.stringify(arr)+'&addrId='+that.data.addrId,
    })
  },
  loadCartNum(){
   let guide = this.selectComponent("#cart")
   guide.loadCount()
  },
  addFoot(){
    let params = {
      footprintType:'mall_product',
      busId:this.data.productId,
      classifyId:this.data.classifyId
    }
    API_Collect.addFoot(params).then(res=>{
    })
  },
  addCart(){
    let that = this
    let params = {'specsId':that.data.specs[that.data.specsIndex].id}
    Api_Mall_Cart.add(params).then(res=>{
      if(res.code == 200){
        // wx.showToast({
        //   title: '添加购物车成功',
        //   duration:1500,
        //   icon:'none'
        // })
        this.addCarAimation();
        this.loadCartNum();
       
      }else{
        wx.showToast({
          title: '暂无库存',
          duration:1500,
          icon:'none'
        })
      }
    })

  },
  addCarAimation :function(){
   
    this.redanimation.translate(30,-70).step({duration: 50});
    this.redanimation.translate(50,-110).step({duration: 50});
    this.redanimation.translate(70,-130).step({duration: 40});
    this.redanimation.translate(85,-110).step({duration: 40});
    this.redanimation.translate(95,-90).step({duration: 30});
    this.redanimation.translate(0,-0).step({duration: 0});
    this.setData({animationData: this.redanimation.export()})
  
  },
  Aimationreset: function () {
    this.redanimation.rotate(0, 0)
                  .scale(1)
                  .translate(0, 0)
                  .skew(0, 0)
                  .step({duration: 0})
    this.setData({animationData: this.redanimation.export()})
  },
  bindSpecsChange(e){
    let specs = this.data.specs[e.detail.value]
    this.setData({
      specsIndex:e.detail.value,
      currentPrice:specs.currentPrice
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadCartNum()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // if(this.data.lastPage)
    //   return
    // let page = this.data.params.pageNum + 1
    // this.setData({
    //   'params.pageNum':page
    // })
    // this.loadComment()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  async initLocation(){
    let that = this
    let lat = getApp().globalData.latitude
    let lon = getApp().globalData.longitude
    if(lat){
      that.reverseLocation(lat,lon)
    }
    wx.getLocation({
      type: 'gcj02',
      // //开启高精准度
      // isHighAccuracy:true,
      // //最多五秒等待
      // highAccuracyExpireTime:5000,
      success: function(res) {
          //纬度
      var latitude = res.latitude
      getApp().globalData.latitude = latitude
      //经度
      var longitude = res.longitude
      getApp().globalData.longitude = longitude
      that.reverseLocation(latitude,longitude)
      // that.data.locationFail=false;
      },
      fail(res){
        that.data.locationFail=true;
        // that.localFail();
      }
    })
  },
  reverseLocation(latitude,longitude,showName){
    let that = this
    qqMapSdk = new QQMapWX({
      key: config.QQMapKey
    });
    qqMapSdk.reverseGeocoder({
      location:{latitude:latitude,longitude:longitude},
      complete(res){
        if(!res.status && res.status==0){
          that.data.locationFail=false;
          let address_reference=res.result.address_reference;
          let locationAddr=res.result.address;
          if(address_reference){
            let landmark_l2=address_reference.landmark_l2;
            if(landmark_l2){
              locationAddr=landmark_l2.title;
            }
            let landmark_l1=address_reference.landmark_l1;
            if(landmark_l1){
              locationAddr=landmark_l1.title;
            }
          }
          if(showName){
            locationAddr=showName;
          }
          const {ad_info} = res.result
          that.setData({
            latitude:latitude,
            longitude:longitude,
            cityName:ad_info.city,
            districtName:ad_info.district
          })
        }else{
          // that.data.locationFail=true;
          // that.localFail();
        }
      }
    })
  },
})